//结算页面
package com.example.homework

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.homework.db.UserDBHelper
import com.example.homework.utils.Prefs

class ResultActivity : AppCompatActivity() {
    private lateinit var username: String
    private var score = 0

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)

        username = intent.getStringExtra("username") ?: ""
        score = intent.getIntExtra("score", 0)

        val account = Prefs.lastAccount(this) ?: ""          // 取本地保存的账号
        val dbHelper = UserDBHelper(this)
        val user = dbHelper.getUserByAccount(account)        // 用已有的方法
        dbHelper.close()

// 防Null
        if (user == null) {
            Toast.makeText(this, "本地账号异常，请重新登录", Toast.LENGTH_SHORT).show()
            startActivity(Intent(this, LoginActivity::class.java))
            finish()
            return
        }

        val tvResult = findViewById<TextView>(R.id.tv_result)
        tvResult.text = "${user.username}，你的得分是：$score\n当前最高分：${user.highScore}"

        val btnPlayAgain = findViewById<Button>(R.id.btn_play_again)
        btnPlayAgain.setOnClickListener {
            val intent = Intent(this, GameActivity::class.java).apply {
                putExtra("username", username)
            }
            startActivity(intent)
            finish()
        }

        val btnBack = findViewById<Button>(R.id.btn_back)
        btnBack.setOnClickListener {
            // 把最新成绩回传
            val data = Intent().apply {
                putExtra("highScore", user.highScore)
            }
            setResult(RESULT_OK, data)
            finish()
        }
    }
}